package requests.math.programmerCalc;

public class ArithmeticOperations {
	
	
	public char[] clearBinary(char binary[]) {
		for (int i = 0; i < binary.length; i++) {
			binary[i] = ' ';
		}
		return binary;
	}
	
	public char[] addiction(char binary[], char binary2[], int max) {
		int carry = 0;
		
		for (int i = max; i >= 0; i--) {
			if (binary[i] != ' ' && binary2[i] != ' ') {
				int val = (int)(binary[i]-48) + (int)(binary2[i]-48) + carry;
				int tmp = val%2;
				carry = val/2;
				binary[i] = (char)(tmp+48);
			}
			else if (binary[i] != ' ') {
				int val = (int)(binary[i]-48) + carry;
				int tmp = val%2;
				carry = val/2;
				binary[i] = (char)(tmp+48);
			}
			else if (binary2[i] != ' ') {
				int val = (int)(binary2[i]-48) + carry;
				int tmp = val%2;
				carry = val/2;
				binary[i] = (char)(tmp+48);			
			}
			else if (carry == 1) {
				binary[i] = (char)(carry+48);
				carry = 0;
			}
			else {
				break;
			}
		}
		return binary;
	}
	
	public char[] multiplication(char binary[], char binary2[], int ptr, int ptr2) {
		
		int val = binToDec(binary, ptr);
		int val2 = binToDec(binary2, ptr2);
		val = val * val2;
		binary = decToBin(val, binary.length-1);
		return binary;
	}
	
	public char[] division(char binary[], char binary2[], int ptr, int ptr2) {
		int val = binToDec(binary, ptr);
		int val2 = binToDec(binary2, ptr2);
		val = val / val2;
		binary = decToBin(val, binary.length-1);
		
		return binary;
	}
	
	public int binToDec(char binary[], int ptr) {
		int result = 0, k = 0;
		for (int i = binary.length-1; i > ptr; i--) {
			result += (int)(binary[i]-48) * (int)Math.pow(2, k);
			k++;
		}
		return result;
	}
	
	public char[] decToBin(int val, int max) {
		char binary[] = new char[max+1];
		binary = clearBinary(binary);
		int k = max;
		while (val > 0) {
			binary[k] = (char)(val%2+48);
			val = val/2;
			k--;
		}
		return binary;
	}
	
	
	public char[] substraction(char binary[], char binary2[], int max) {
		for (int i = max; i >= 0; i--) {
			if (binary[i] == '1' && binary2[i] == '1') {
				binary[i] = '0';
			}
			else if(binary[i] == '1' && (binary2[i] == '0' || binary2[i] == ' ')) {
				binary[i] = '1';
			}
			else if(binary[i] == '0' && (binary2[i] == '0' || binary2[i] == ' ')) {
				binary[i] = '0';
			}
			else if(binary[i] == '0' && binary2[i] == '1') {
				int k = 1;
				while (binary[i] == '0') {
					if (binary[i-k] == '1') {
						binary[i-k] = '0';
						binary[i] = '1';
						break;
					}
					else {
						binary[i-k] = '1';
						k++;
					}
						
				}
			}
			else {
				for (int j = i; j >= 0; j--) {
					binary[j] = ' ';
				}
			}
			
		}
		
		return binary;
	}	

}
